<?php

namespace App\Http\Controllers;

use App\Http\Requests\Partitions\ChangeTableRequest;
use App\Http\Requests\Partitions\ChangeTableUserRequest;
use App\Http\Requests\Partitions\ClearTableRequest;
use App\Http\Requests\Partitions\IndexRequest;
use App\Http\Requests\Partitions\OpenTableRequest;
use App\Http\Requests\Partitions\RollbackRequest;
use App\Http\Requests\Partitions\StoreRequest;
use App\Http\Requests\Partitions\StoreTableRecordRequest;
use App\Http\Requests\Partitions\TableListRequest;
use App\Models\PartitionAdjustmentAmount;
use App\Models\PartitionTableRecord;
use App\Services\Java\ApiService;
use App\Services\Login;
use App\Services\Partition;
use App\Services\PHP\PhpApiService;
use D1M\Common\Exceptions\BusinessException;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use D1M\Common\Helpers\Result;
use Illuminate\Http\Request;

class PartitionController extends Controller
{

    /***********************************pos前端提供给Java************************************/
    /**
     * 门店所有使用中记录
     */
    public function storeTableRecord(StoreTableRecordRequest $request,Partition $service)
    {
        $data = $request->post('data');
        $res = $service->storeTableRecord($data);
        return Result::success($res);
    }

    /**
     * 零售单调整金额回滚
     */
    public function rollbackAdjustment(RollbackRequest $request,Partition $service)
    {
        //todo 做log记录 失败怎么处理？
        $data = $request->post('data');
        $service->rollbackAdjustment($data);
        return Result::success();
    }





    /***********************************pos管理台面提供给Java*********************************/
    /**
     * 列表
     * @param IndexRequest $request
     * @param Partition $service
     * @return array
     */
    public function index(IndexRequest $request,Partition $service)
    {
        $storeId = $request->post('data')['store_id'];
        $res = $service->list($storeId);
        return Result::success($res);
    }




    /**
     * 保存
     * @param StoreRequest $request
     * @param Partition $service
     * @return array
     */
    public function store(StoreRequest $request,Partition $service)
    {
        $data = [
            'partitions'=>$request->post('data')['partitions'],
            'store_id'=>$request->post('data')['store_id']
        ];
//        $res = $service->store($data);
        $res = $service->storeNew($data);
        return Result::successMsg($res);

    }

    /**
     * 区域排序
     * @param Request $request
     * @param Partition $service
     * @return array
     */
    public function order(Request $request,Partition $service)
    {
        //排序（上移、下移）
        $ids = $request->post('data')['ids'];
        $res = $service->partitionOrder($ids);
        return Result::successMsg($res);
    }


    /**
     * 删除区域
     * @param Partition $service
     * @param Request $request
     * @return array
     */
    public function destroy(Partition $service,Request $request)
    {
        $id = $request->post('data')['id'];
        $res = $service->deletePartition($id);
        return Result::successMsg($res);
    }


    /**
     * 桌台
     * 启用、停用
     * @param Partition $service
     * @param Request $request
     * @return array
     */
    public function changeTableState(Partition $service,Request $request)
    {
        $id = $request->post('data')['id'];
        $res = $service->changeState($id);
        return Result::successMsg($res);
    }


    /**
     * 桌台删除
     * @param Partition $service
     * @param Request $request
     * @return array
     */
    public function softDeleteTable(Partition $service,Request $request)
    {
        $id = $request->post('data')['id'];
        $res = $service->deleteTable($id);
        return Result::successMsg($res);
    }

    /**
     * 生成桌台二维码
     */
    public function qrcode(Partition $service,Request $request)
    {
        $id = $request->post('id');
        $res = $service->generateQrcode($id);
        return Result::success(['image'=>$res]);
    }



    /************************************ pos 前端 ************************************/


    /**
     * 台面概览
     *
     */
    public function partitionTable(Partition $service,TableListRequest $request)
    {
        $params = $request->only(['store_id','partition_id','state']);
        $res = $service->tableList($params);

        return Result::success($res);
    }

    /**
     * 开台
     * @partition_table_id 桌台ID
     * @manage_no 用户手机号 非必须
     * @actual_number 就餐人数
     */
    public function openTable(Partition $service,OpenTableRequest $request,ApiService $api,Login $login)
    {
        $params = $request->only(['partition_table_id','manage_no','actual_number']);
        //请求Java 获取餐饮单号 并记录进开台记录
        //获取门店ID 暂时只有一个可用
//        $me = $login->me($request);
//        $javaParams = [
//            'storeId'=>$me->shop_id,
//            'deskNo'=>$params['partition_table_id']
//        ];
        //$data = $api->requestJava('/food/api/order/getByDesk',$javaParams,'post');
//        $data = [
//            "orderNo"=> "20230706132408000002",
//            "sumPrice"=> 0
//        ];
        //$params['food_order_no'] = $data['orderNo'];
        $res = $service->openTable($params);

        return Result::success($res);
    }

    /**
     * 清台
     * @partition_table_id 桌台ID
     */
    public function clearTable(Partition $service,ClearTableRequest $request,ApiService $api)
    {
        $params = $request->only(['partition_table_id']);
        $id = $params['partition_table_id'];

        $where = [
            'partition_table_id'=>$id,
            'cleared'=>0//服务中
        ];
        $recordId = PartitionTableRecord::where($where)->first();
        if(!$recordId){
            return Result::fail('该桌台不符合清桌条件');
        }

        //调java回滚库存
        $api->requestJava('/food/api/order/over',['deskRecordId'=>$recordId->id],'post');

        $res = $service->clearTable($id,$where);
        return Result::successMsg($res);
    }

    /**
     * 换桌
     * @original_partition_table_id 原桌台ID
     * @partition_table_record_id 使用记录ID
     * @partition_table_id 目标桌台ID
     */
    public function changeTable(Partition $service,ChangeTableRequest $request,ApiService $api)
    {
        $params = $request->only(['partition_table_id','original_partition_table_id','partition_table_record_id']);
        //去查询有没有订单  如果有且已结账不可换桌
//        $orderInfo = PartitionTableRecord::where('id',$params['partition_table_record_id'])->first(['order_no']);
//
//        if($orderInfo && $orderInfo->order_no){
//            //查询订单状态
//            $data = $api->requestJava('/order/api/order-record/query-state',['no'=>$orderInfo->order_no],'post');
//            if($data && $data['state']==5) throw new BusinessException('订单已结账不支持换桌');
//        }

        $res = $service->changeTable($params);
        return Result::successMsg($res);
    }


    /**
     * 切换用户
     */
    public function changeTableUser(Partition $service,ChangeTableUserRequest $request)
    {
        $params = $request->only(['partition_table_record_id','manage_no']);
        $res = $service->changeUser($params);
        return Result::successMsg($res);
    }


    /**
     * 台面明细
     * @param Partition $service
     * @param Request $request
     * @return array
     */
    public function tableDetail(Partition $service,Request $request,ApiService $api)
    {
        $tableId = $request->get('partition_table_id');
        //台面信息
        $table = $service->tableDetail($tableId);
        //用户信息
        $user = $order = $coupon = $adjustment = [];
        if($table['manage_no']){
            //对接Java接口  用户手机号中间四位隐藏
            $user = $api->requestJava('/auth/api/user/userInfoByManageNo',
                ['manageNo'=>$table['manage_no']],'post');
        }
        //点餐信息
//        if($table['partition_table_record_id']) {
//            //todo 对接Java接口
////            $order = $api->requestJava('/food/api/order/detail',
////                ['orderNo'=>$table['food_order_no']],'post');
//            $order = $api->requestJava('/food/api/order/getByDesk',
//                ['deskRecordId'=>$table['partition_table_record_id']],'post');
//
//            //调整金额相关 todo 拿餐饮单号去查询优惠券和调整金额
//            $reduceAmount = PartitionAdjustmentAmount::where(['order_no'=>$table['food_order_no'],'order_type'=>0])
//                ->orderBy('id','desc')
//                ->get(['order_no','manage_no','login_name','init_amount','after_amount','reduce_id','reduce_amount','reduce_description','adjustment_type'])
//                ->toArray();
//            //dump($reduceAmount);
//
//            foreach ($reduceAmount as $v)
//            {
//                if($v['adjustment_type']==0)array_push($coupon,$v);
//                if($v['adjustment_type']==1)array_push($adjustment,$v);
//            }
//        }
        $res = [
            'table'=>$table,
            'user'=>$user,
//            'order'=>$order,
//            'coupon'=>$coupon,
//            'adjustment'=>$adjustment
        ];
        return Result::success($res);
    }

    /**
     * 提交账单明细
     * @param Partition $service
     * @param Request $request
     * @return array
     */
    public function tableFoodOrderDetail(Partition $service,Request $request,ApiService $api)
    {
        $params =$request->only(['partition_table_id','order_no']);

        //台面信息
        $table = $service->tableDetail($params['partition_table_id']);

        //用户信息
        $user  = $coupon = $adjustment = [];
        if($table['manage_no']){
            //对接Java接口  用户手机号中间四位隐藏
            $user = $api->requestJava('/auth/api/user/userInfoByManageNo',
                ['manageNo'=>$table['manage_no']],'post');
        }

        //对接Java接口餐饮单详情
        $order = $api->requestJava('/food/api/order/detail',
            ['orderNo'=>$params['order_no']],'post');

        //调整金额相关
//        $reduceAmount = PartitionAdjustmentAmount::where(['order_no'=>$params['order_no'],'order_type'=>0])
//            ->orderBy('id','desc')
//            ->get(['order_no','manage_no','login_name','init_amount','after_amount','reduce_id','reduce_amount','reduce_description','adjustment_type'])
//            ->toArray();


//        foreach ($reduceAmount as $v)
//        {
//            if($v['adjustment_type']==0)array_push($coupon,$v);
//            if($v['adjustment_type']==1)array_push($adjustment,$v);
//        }

        $res = [
            'table'=>$table,
            'user'=>$user,
            'order'=>$order,
//            'coupon'=>$coupon,
//            'adjustment'=>$adjustment
        ];
        return Result::success($res);
    }




    /**
     * @param ApiService $service
     * @param Request $request
     * @return array
     */
    public function getSign(ApiService $service,Request $request)
    {

        $service->testException(1);
    }

    public function getToken(ApiService $service,Request $request)
    {
        $data = [
            'orderNo'=>'20230707134329000001',
            'detailList'=>[
                [
                    'productOnlineId'=>13,
                    'productSpecOnlineId'=>45,
                    'qty'=>1,
                ]
            ]
        ];
        $res = $service->requestJava('/get_sign',$data,'get');
        return Result::success($res);
    }

    public function getPhpSign(PhpApiService $service,Request $request,Login $login)
    {
        $data = $request->post('data');
        $nonce = $request->get('nonce');
        $timestamp = $request->get('timestamp');
        $signature = $request->get('signature');
        $token = trim(str_replace('Bearer', '', $request->header('Authorization')));
        $sign = $service->checkSignature($nonce,$timestamp,$signature,$token,$data);
        return Result::success($sign);
    }

    public function getPhpToken(Login $service,Request $request)
    {
        $appid = $request->post('data')['appid'];
        if($appid !=env("PAWHUB_APP_ID"))
        {
            return Result::fail('参数异常',-1001);
        }
        $data = [
            'id'=>$appid
        ];
        $res = $service->generatorToken($data);
        return Result::success($res);

    }

    public function refreshPhpToken(Login $service,Request $request)
    {
        $res = $service->refershToken($request);
        return Result::success($res);
    }







}
